Go Optimizations 101 (20240316) by Tapir Liu
Author:Tapir Liu
Language: eng
Format: epub
Small-size structs are optimized specially
This has been talked about in value copy costs and small-size types/values.
Make struct size smaller by adjusting field orders
Struct field orders might affect struct sizes, which has been mentioned in a previous chapter.
Arrays and Slices
Avoid using literals of large-size array types as comparison operands
For example, in the following code, the function CompareWithGlobalVar is more performant than the function CompareWithLiteral (for the official standard Go compiler v1.22.n).
package arrays import "testing" type T [1000]byte var zero = T{} func CompareWithLiteral(t *T) bool { return *t == T{} } func CompareWithGlobalVar(t *T) bool { return *t == zero } var x T var r bool func Benchmark_CompareWithLiteral(b *testing.B) { for i := 0; i < b.N; i++ { r = CompareWithLiteral(&x) } } func Benchmark_CompareWithGlobalVar(b *testing.B) { for i := 0; i < b.N; i++ { r = CompareWithGlobalVar(&x) } }
The benchmark results:
Benchmark_CompareWithLiteral-4 21214032 52.18 ns/op Benchmark_CompareWithGlobalVar-4 36417091 31.03 ns/op
By using the -S compiler option, we could find that the compile generates less instructions for the function CompareWithGlobalVar than the function CompareWithLiteral. That is why the function CompareWithGlobalVar is more performant.
For small-size arrays, the performance difference between the two functions is small.
Please note that future compiler versions might be improved to remove the performance difference between the two functions.
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
The Art of Coaching Workbook by Elena Aguilar(48569)
Trainspotting by Irvine Welsh(20139)
Twilight of the Idols With the Antichrist and Ecce Homo by Friedrich Nietzsche(17751)
The Secret History by Donna Tartt(16760)
Cat's cradle by Kurt Vonnegut(13952)
Ready Player One by Cline Ernest(12929)
All the Missing Girls by Megan Miranda(12832)
Talking to Strangers by Malcolm Gladwell(11981)
Fangirl by Rainbow Rowell(7892)
Thirteen Reasons Why by Jay Asher(7855)
The Compound Effect by Darren Hardy(7638)
The remains of the day by Kazuo Ishiguro(7623)
Periodization Training for Sports by Tudor Bompa(7375)
The Lover by Duras Marguerite(7163)
Wonder by R. J. Palacio(7123)
Tools of Titans by Timothy Ferriss(7020)
Change Your Questions, Change Your Life by Marilee Adams(6702)
The Complete Stick Figure Physics Tutorials by Allen Sarah(6674)
The Leavers by Lisa Ko(6516)